package utils.wechat;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import models.SystemParams;
import play.cache.Cache;
import services.SystemParamService;
import services.WeChatService;
import utils.BizConstants;
import vos.weChat.TokenVo;

public class TokenUtil {
	private static final SimpleDateFormat dateTimeFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**
	 * 获取实时token 
	 *
	 * @Title: getAccess_token 
	 * @param APPID
	 * @param APPSECRET
	 * @return
	 * @return: TokenVo
	 */
	private static TokenVo getAccess_token(){ 
	         String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+BizConstants.WECHAT_APPID+"&secret="+BizConstants.WECHAT_APPSECRET;
	         String accessToken = null;
	         String expires_in=null;
	         String message=HttpUtil.doGet(url);
	         JSONObject demoJson = JSON.parseObject(message);
             accessToken = demoJson.getString("access_token");
             expires_in=demoJson.getString("expires_in");
             TokenVo vo=new TokenVo(accessToken,expires_in);
             vo.tokentime=dateTimeFormater.format(new Date());
             /**
              * 更新缓存和数据库
              */
		    String tokvo=JSON.toJSONString(vo);
		    Cache.add("weChat_token", tokvo);
		    SystemParams param=new SystemParams("wechat_token",tokvo,"");
		    SystemParamService.saveParam(param);
		    return vo;
		}
	 	/**
	    * 获取token
	    * @param aPPSECRET 
	    * @param aPPID 
	    * @Title: getAccessToken 
	    * @return: void
	    */
	   public static String getAccessToken(){
		   TokenVo vo=WeChatService.getTokenByCache();
		   if(vo==null){
			   vo=getAccess_token();
		   }
		   else{
			   Date date=new Date();
			   String tokentime=vo.tokentime;
			   Date tokTime=null;
			   try {
				   tokTime=dateTimeFormater.parse(tokentime);
				   long value=(date.getTime()-tokTime.getTime())/1000;
				   if(value>Long.parseLong(vo.expiresin)){
					   vo=getAccess_token();
				   }
			   } catch (ParseException e) {
					// TODO Auto-generated catch block
				   e.printStackTrace();
			   }
		   }
		return vo.token;   
		   
	   }
}
